﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace BullShitPoker
{
    static class Client
    {
        private static bool client_running;
        // Сокет клиента
        private static Socket client;
        // Адрес сервера
        private static IPAddress ip; 
        // Порт, по которому будем присоединяться
        private static int port = 5555;
        private static string name;
        // Список потоков
        private static List<Thread> threads = new List<Thread>();
        private static string Server;

        public static bool init(string server, string n)
        {
            if (server == "localhost") server = "127.0.0.1";
            Server = server;
            name = n;
            try
            {
                ip = IPAddress.Parse(server);
                client_running = true;
                //if (client.Connected) client.Close();
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(ip, port);
                client.NoDelay = true;
                client.Send(Encoding.UTF8.GetBytes(name));
                Receiver();
            }
            catch { return false; }
            return true;
        }

        private static void Receiver()
        {
            Thread th = new Thread(delegate()
            {
                while (client_running)
                {
                    try
                    {
                                byte[] bytes = new byte[1024];
                                // Принимаем
                                client.Receive(bytes);
                                string Request = Encoding.UTF8.GetString(bytes, 0, bytes.Length).Trim();
                                if (Request.IndexOf('\0') > 0) Request = Request.Remove(Request.IndexOf('\0'));
                                string[] args = Request.Split('\n');
                                foreach (string arg in args)
                                {
                                    string str = arg.Replace('\a', '\n');
                                    if (str.Length != 0)
                                    {
                                        char[] sep = { '\n' };
                                        string[] s = str.Split(sep, 2);
                                        switch (s[0])
                                        {
                                            case "RoundStart":
                                                Worker.RoundStart();
                                                break;
                                            case "Chat":
                                                Worker.Chat(s[1]);
                                                break;
                                            case "NextMove":
                                                Worker.NextMove(s[1]);
                                                break;
                                            case "StopGame":
                                                Worker.NewGame();
                                                break;
                                        }
                                    }
                                }
                        }
                    catch { }
                }
            });
            th.Start();
            threads.Add(th);
        }

        public static string Sender(string msg)
        {
            TcpClient tcpClient;
            NetworkStream networkStream;
            StreamReader streamReader;
            StreamWriter streamWriter;
            
            try
            {
                tcpClient = new TcpClient(Server, port + 1);
                

                streamReader = new StreamReader(tcpClient.GetStream());
                streamWriter = new StreamWriter(tcpClient.GetStream());
                
                streamWriter.WriteLine(msg.Replace('\n', '\a'));
                streamWriter.Flush();
                string s = streamReader.ReadLine();
                streamWriter.Close();
                if (s == null) s = "";
                s = s.Replace('\a', '\n');
                return s;
            }
            catch (Exception e) { 
                File.AppendAllText("log.txt", DateTime.Now.ToString() + " " + e.Message + " " + msg + " " + "\n");
               return "";
            }        
        
        }

        public static void Close()
        {
            if (client != null) client.Close();
            foreach (Thread th in threads)
            {
                th.Abort();
            }
            threads.Clear();
        }
    }
}
